package com.ostms.adv.play;

import android.annotation.SuppressLint;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.google.gson.Gson;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.ostms.adv.R;
import com.ostms.adv.model.ActInfo;
import com.ostms.adv.model.AdvInfo;
import com.ostms.adv.model.AdvRequestModle;
import com.ostms.adv.model.RecordModle;
import com.ostms.adv.utils.CommonUtils;
import com.ostms.adv.utils.HttpTools;
import com.ostms.adv.utils.LOG;
import com.ostms.adv.utils.Md5Util;
import com.ostms.adv.utils.Tools;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.MultipartBody;

/**
 * Created by sun on 2018/8/3.
 */

public class PayPlayManager {
    Handler handler;

    private static final String TAG = PayPlayManager.class.getSimpleName();
    private Context context;
    private LOG log;
    //广告视图管理器
    private AdvertiseViewManager viewManager;

    private OstmsStadbyPlay ostmsStandbyPlayer;
    private BaiduVideoPlay baiduVideoPlayer;
    private Group2Play group2Player;
    //true -可以播放
    private ImageLoader imageLoader;
    private HttpTools httpTools;

    //底部广告
    private LinearLayout bottomLinearLayView;

    public PayPlayManager(Context context, HttpTools httpTools, ImageLoader imageLoader, Handler handler) {
        this.context = context;
        this.handler = handler;
        this.httpTools = httpTools;
        this.imageLoader = imageLoader;
    }

    /**
     * 注册所有的广告视图
     *
     * @param views
     */
    public void registerAllAdvertiseView(View[] views) {
        viewManager = new AdvertiseViewManager(views);
    }

    /**
     * 注册奥森待机广告播放器,组合1播放器
     */
    private ImageView topView;

    public void registerOstmsGroup1View(View view, ImageView topView) {
        this.ostmsStandbyPlayer = new OstmsStadbyPlay(view, topView);
        this.topView = topView;
    }

    private View groupAdv;

    public void registerOstmsGroup2View(View view, ImageView topView, TextureView textureView) {
        this.group2Player = new Group2Play(view, topView, textureView);
        groupAdv = view;
    }

    public void setGroup2Surface(Surface surface) {
        group2Player.setSurface(surface);
    }

    public void setBaiduVideoSurface(Surface surface) {
        baiduVideoPlayer.setSurface(surface);
    }

    public void registerBaiduVideoView(LinearLayout group_baidu_video) {
        this.baiduVideoPlayer = new BaiduVideoPlay(group_baidu_video);
        this.group_baidu_video = group_baidu_video;
    }

    public void registerBottomView(LinearLayout bottomView) {
        this.bottomLinearLayView = bottomView;
    }

    private LinearLayout group_baidu_video;

    /**
     * 广告视图管理器
     */
    private class AdvertiseViewManager {

        private View[] views;

        private AdvertiseViewManager(View[] views) {
            this.views = views;
        }

        /**
         * 隐藏所有视图
         */
        private void hideAllView() {
            for (View view : views) {
                view.setVisibility(View.GONE);
            }
        }

        /**
         * 显示某个视图
         *
         * @param view
         */
        private void display(View view) {
            hideAllView();
            view.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 计算广告对应的本地缓存的绝对地址
     *
     * @param advInfo
     * @return
     */
    private void reckon(AdvInfo advInfo) {
        if (null != advInfo) {
            String dir = CommonUtils.ADV_PATH + (isVedio(advInfo) ? "/video" : "/image");
            String url = advInfo.getUrl();
            String suffix = url.substring(url.lastIndexOf(".") + 1, url.length());
            String fileName = advInfo.getAdvCode() + "." + suffix;
            String path = Environment.getExternalStorageDirectory().getAbsolutePath() + dir + "/" + fileName;
            advInfo.setPath(path);
        }
    }

    List<String> vedioList = Arrays.asList("mp4", "avi", "mov", "asf", "wmv", "rm");
    List<String> imageList = Arrays.asList("jpg", "png", "gif", "jpeg", "bmp");

    private boolean isVedio(AdvInfo advInfo) {
        String type = advInfo.getUrl().substring(advInfo.getUrl().lastIndexOf(".") + 1);
        if (vedioList.contains(type)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 根据path 检查文件是否存在
     *
     * @param advInfo
     * @return
     */
    private boolean exists(AdvInfo advInfo) {
        File file = new File(advInfo.getPath());
        file.setLastModified(new Date().getTime());
        return file.exists();
    }

    private boolean reckonAndCheckExists(AdvInfo advInfo) {
        if (null != advInfo) {
            reckon(advInfo);
            return exists(advInfo);
        }
        return false;
    }

    private void standbyVideoPlayBegin(View view, final AdvInfo adv, final String type, final String price) {
        viewManager.display(view);
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                ostmsStandbyPlayer.ostmsStandbyPlayStart();
            }
        }, Tools.getRandomNum(3, 13, 1));
        adv.setTriggerTime(new Date().getTime() + "");
        //adv.setCode(Md5Util.MD5(new Date().getTime() + OstmsApp.getEquipmentCode()));
        adv.setCode(Md5Util.MD5(new Date().getTime() + Tools.initEquipmentCode()));
        //String equipmentCode =  Tools.initEquipmentCode();
        baiduVideoPlayer.play(adv.getPath(), new VideoPlay() {
            @Override
            public void onPlayCompletion() {
                List<AdvInfo> list = new ArrayList<>();
                list.add(adv);
                Log.i(TAG, "onPlayCompletion: 传给播放记录"+type+price);
                record(list, false,type,price);
                standbyPlay();
            }
        });
    }

    public void standbyPlay() {
        //播放待机
        ostmsStandbyPlayer.playStandby();
    }


    public void standbyStop() {
        ostmsStandbyPlayer.stop();
    }

    public void closePlay() {
        if (null != mMediaPlayer) {
            if (mMediaPlayer.isPlaying()) {
                mMediaPlayer.stop();
            }
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
        if (null != handler) {
            handler.removeCallbacksAndMessages(null);
        }
    }

    /**
     * 待机广告播放
     */
    private class Group1Play {
        //整个视图
        private View view;
        //上部图片视图
        private ImageView topView;

        private Group1Play(View view, ImageView topView) {
            this.view = view;
            this.topView = topView;
        }

        protected void play(final AdvInfo advInfo, final String type, final String price) {
            final List<AdvInfo> list = new ArrayList<>();
            advInfo.setTriggerTime(new Date().getTime() + "");
            advInfo.setCode(Md5Util.MD5(new Date().getTime() + Tools.initEquipmentCode()));
            handler.post(new Runnable() {
                @Override
                public void run() {
                    if (null != advInfo.getWinNoticeUrl()) {
                        //播放百度
                        viewManager.display(view);
                        String rePath = "drawable://" + R.drawable.start_top;
                        if (null != advInfo) {
                            if (null != advInfo.getPath()) {
                                rePath = "file://" + advInfo.getPath();
                            } else if (null != advInfo.getUrl()) {
                                rePath = advInfo.getUrl();
                            }
                        }
                        imageLoader.displayImage(rePath, topView);
                        list.add(advInfo);
//                        record(list, false);
                    } else if (advInfo.isDrawable()) {
                        //播放指定内容
                        viewManager.display(view);
                        imageLoader.displayImage(advInfo.getDrawablePath(), topView);
                    } else {
                        viewManager.display(view);
                        String rePath = "drawable://" + R.drawable.start_top;
                        if (null != advInfo) {
                            if (null != advInfo.getPath()) {
                                rePath = "file://" + advInfo.getPath();
                            } else if (null != advInfo.getUrl()) {
                                rePath = advInfo.getUrl();
                            }
                        }
                        imageLoader.displayImage(rePath, topView);
//                        if (!"ostms".equals(advInfo.getPlatform_type())) {
//                            list.add(advInfo);
////                            record(list, false);
//                        }
                        list.add(advInfo);
                    }
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            ostmsStandbyPlayer.ostmsStandbyPlayStart();
                        }
                    }, Tools.getRandomNum(3, 14, 1));


                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            record(list, false,type,price);
                            standbyPlay();
                        }
                    }, 15 * 1000);
                }
            });
        }
    }

    public void attempts(final Surface surface, final Attempts attempts) {
        System.out.println("surface==" + surface);
        if (surface != null) {
            attempts.ok();
        } else {
            standbyPlay();
        }
    }

    public interface Attempts {
        void ok();
    }


    public class Group2Play {
        //整个视图
        private View view;
        //顶部图片
        private ImageView topView;
        //中部视频
        private TextureView textureView;
        private Surface surface = null;

        private Group2Play(View view, ImageView topView, TextureView textureView) {
            this.view = view;
            this.topView = topView;
            this.textureView = textureView;
        }

        public void setSurface(Surface surface) {
            this.surface = surface;
        }

        private void play(final AdvInfo topAdv, final String videoPath, final VideoPlay player) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    attempts(surface, new Attempts() {
                        @Override
                        public void ok() {
                            if (null != videoPath) {
                                player.play(surface, videoPath);
                            } else {
                                handler.postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        System.gc();
                                        player.release();
                                        player.onPlayCompletion();
                                    }
                                }, 10 * 1000);
                            }
                        }
                    });
                    if (null != topAdv) {
                        String rePath;
                        if (null != topAdv.getPath()) {
                            rePath = "file://" + topAdv.getPath();
                        } else {
                            rePath = topAdv.getUrl();
                        }
                        imageLoader.displayImage(rePath, topView);
                    } else {
                        imageLoader.displayImage(null, topView);
                    }
                }
            });
        }
    }

    public class BaiduVideoPlay {
        //整个视图
        private View view;
        //中部视频
        private Surface surface;

        public BaiduVideoPlay(View view) {
            this.view = view;
        }

        public void setSurface(Surface surface) {
            this.surface = surface;
        }

        private void play(final String videoPath, final VideoPlay player) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    attempts(surface, new Attempts() {
                        @Override
                        public void ok() {
                            if (null != videoPath) {
                                player.play(surface, videoPath);
                            } else {
                                handler.postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        System.gc();
                                        player.release();
                                        player.onPlayCompletion();
                                    }
                                }, 8 * 1000);
                            }
                        }
                    });
                    viewManager.display(view);
                }
            });
        }
    }

    private class OstmsStadbyPlay extends Group1Play {
        private static final int EMPTYPLAYERSUCCESS = 5;
        private static final int EMPTYPLAYERFAILURE = 6;
        private int index = 0;
        private int indexDefault = 0;
        private AdvInfo advInfo;
        @SuppressLint("HandlerLeak")
        private Handler mHanler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == EMPTYPLAYERSUCCESS) {//缓存待机广告
                    AdvRequestModle advRequestModle = (AdvRequestModle) msg.obj;
                    Gson gson = new Gson();
                    String json = gson.toJson(advRequestModle);
                    Tools.setProperties(context, CommonUtils.ADV_STANDBY, json);
                } else if (msg.what == EMPTYPLAYERFAILURE) {
                    Tools.setProperties(context, CommonUtils.ADV_STANDBY, "");
                }
            }
        };

        private OstmsStadbyPlay(View view, ImageView topView) {
            super(view, topView);
        }

        public void playStandby() {
            advInfo = null;
            String advJson = Tools.getAdvStandby(context);
            if (null == advJson || advJson.length() < 1) {
                advJson = Tools.getDefaultAdv(context);
                bottomLinearLayView.setVisibility(View.GONE);
            }else{
                bottomLinearLayView.setVisibility(View.VISIBLE);
            }
            Gson gson = new Gson();
            final AdvRequestModle advRequestModle = gson.fromJson(advJson, AdvRequestModle.class);
            if (null != advRequestModle) {
                List<AdvInfo> ads = advRequestModle.getAds();
                if (null != ads && ads.size() > 0) {
                    if (ads.size() != 2) {
                        if (ads.size() == 1) {
                            advInfo = advRequestModle.getAds().get(0);
                        } else if (ads.size() > 2) {
                            int temp = indexDefault % ads.size();
                            indexDefault++;
                            advInfo = advRequestModle.getAds().get(temp);
                        }
                        if (isVedio(advInfo)) {
                            if (reckonAndCheckExists(advInfo)) {
                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        standbyVideoPlayBegin(group_baidu_video, advInfo,advRequestModle.getPriceType(),advRequestModle.getPlayPriceStr());
                                    }
                                });
                            } else {
                                fileMissCache(advInfo, new DownloadUtilsListener() {
                                    @Override
                                    public void onComplete() {
                                        standbyVideoPlayBegin(group_baidu_video, advInfo,advRequestModle.getPriceType(),advRequestModle.getPlayPriceStr());
                                    }
                                });
                            }
                        } else {
                            if (reckonAndCheckExists(advInfo)) {
                                play(advInfo,advRequestModle.getPriceType(),advRequestModle.getPlayPriceStr());
                            } else {
                                //下载
                                fileMissCache(advInfo, new DownloadUtilsListener() {
                                    @Override
                                    public void onComplete() {
                                        play(advInfo,advRequestModle.getPriceType(),advRequestModle.getPlayPriceStr());
                                    }
                                });
                            }
                        }
                    } else {
                        //美数组合广告
                        ActInfo actInfo = new ActInfo();
                        actInfo.setAds(ads);
                        group2Play1(actInfo, groupAdv,advRequestModle.getPriceType(),advRequestModle.getPlayPriceStr());
                    }
                } else {
                    int temp = index % 5;
                    index++;
                    AdvInfo advInfo1 = getDrawableList().get(temp);
                    play(advInfo1,advRequestModle.getPriceType(),advRequestModle.getPlayPriceStr());
                }
            } else {
                int temp = index % 5;
                index++;
                AdvInfo advInfo1 = getDrawableList().get(temp);
                play(advInfo1,"","");

            }
        }

        public void ostmsStandbyPlayStart() {
            String path = CommonUtils.BAIDUSTANDBY;
            FormBody.Builder builder = new FormBody.Builder();
            builder.add("equipmentCode", Tools.initEquipmentCode());
            httpTools.sendPostdata(path, builder, new HttpTools.HttpLisenner() {
                @Override
                public void onFailure(Call call, IOException e) {
                    log.i(TAG, "待机请求失败:" + e);
                    mHanler.sendEmptyMessage(EMPTYPLAYERFAILURE);
                }

                @Override
                public void onResponse(Call call, String result) {
                    log.i(TAG, "待机请求成功:" + result);
//                    result = "{\"ads\":[{\"advCode\":\"D20190725171749508277\",\"advName\":\"SSP平台广告-视频-1200×675\",\"advType\":\"3\",\"cameFrom\":\"2\",\"cid\":\"6b60e1c6665075a8ab2cc2c7deb40979\",\"conCode\":\"meishu666\",\"createTime\":1564049870919,\"creator\":\"system\",\"id\":\"4be729dbf60142d1a4d8a9aff80058c7\",\"isSearch\":\"0\",\"modifier\":\"system\",\"modifyTime\":1564049870919,\"page\":1,\"rows\":10,\"status\":\"1\",\"url\":\"http://129.204.64.118:88/ostmsAdv/test_adv/meishu/2019/07/25/D20190725171749508277/d5ba41b1861b1b427b60050cfa1ace12.mp4\",\"winNoticeUrl\":\"http://dsp.1rtb.com/imp?ext_data=b2lkPTExMDAyNDg4NjEsY2lkPTg5ODYwNDA0MTAxODcwNTA1MDg5LHV1aWQ9VUROZUJKVTNtVWpuelllVjhzM2pWcixtZT1tcyxleD03MjIscGM9MCxsaWQ9LG5hdD0xLHZyPTAsdmV4PTcyMix1dD0xNTY0MDQ5ODcwLGRvbT0scGlkPTEwMDQ2Mzgsb2NjPWNpbSxjY3A9ODAwMDAwMDAsYWlkPTExMDAzMTk4NTMseT0wLGF2PTAsb3NpZD0yLGNwPTAsdmNwPTA%3D&ver=1&reqid=722&price=4Z1L8CcDOhup5MozA3BpYg,http://ssp.1rtb.com/imp?ua=&ssp_req_id=37432cd92672b3bdd88125d3a3df5985&dsp_req_id=a18d43366d6b398acf9aad56bde08372&strategy_dealid=5859&media_id=101288&accept_id=10233&adv_id=1004638&creative_id=211407&account_id=199497&price=sspMTAw&pre=sspMA==&signature=d3c79a8af8cd0137e3e7be2eea863657\"},{\"advCode\":\"D20190725171754794405\",\"advName\":\"SSP平台广告-图片-1200×765\",\"advType\":\"5\",\"cameFrom\":\"2\",\"cid\":\"19776592c39627cbf126cb5bcb713e5a\",\"conCode\":\"meishu666\",\"createTime\":1564049870925,\"creator\":\"system\",\"id\":\"c1527f50a5be420eb8a884d2b5a1fd5d\",\"isSearch\":\"0\",\"modifier\":\"system\",\"modifyTime\":1564049870925,\"page\":1,\"rows\":10,\"status\":\"1\",\"url\":\"http://129.204.64.118:88/ostmsAdv/test_adv/meishu/2019/07/25/D20190725171754794405/a00ffb7d46a83a51c5da1b6b0e8ff48d.jpg\",\"winNoticeUrl\":\"http://dsp.1rtb.com/imp?ext_data=b2lkPTExMDAyNDg4NjEsY2lkPTg5ODYwNDA0MTAxODcwNTA1MDg5LHV1aWQ9VUROZUJKVTNtVWpuelllVjhzM2pWcixtZT1tcyxleD03MjIscGM9MCxsaWQ9LG5hdD0xLHZyPTAsdmV4PTcyMix1dD0xNTY0MDQ5ODcwLGRvbT0scGlkPTEwMDQ2Mzgsb2NjPWNpbSxjY3A9ODAwMDAwMDAsYWlkPTExMDAzMTk4NTMseT0wLGF2PTAsb3NpZD0yLGNwPTAsdmNwPTA%3D&ver=1&reqid=722&price=4Z1L8CcDOhup5MozA3BpYg,http://ssp.1rtb.com/imp?ua=&ssp_req_id=37432cd92672b3bdd88125d3a3df5985&dsp_req_id=a18d43366d6b398acf9aad56bde08372&strategy_dealid=5859&media_id=101288&accept_id=10233&adv_id=1004638&creative_id=211407&account_id=199497&price=sspMTAw&pre=sspMA==&signature=d3c79a8af8cd0137e3e7be2eea863657\"}],\"triggerCode\":\"e8147f8d8a51f30c4f40ed98495da8c5\",\"type\":\"2\"}";
                    try {
                        if (!TextUtils.isEmpty(result)) {
                            Gson gson = new Gson();
                            AdvRequestModle advRequestModle = gson.fromJson(result, AdvRequestModle.class);
                            if (null != advRequestModle.getAds() && advRequestModle.getAds().size() > 0&&null!=advRequestModle.getPriceType()) {
                                Log.i(TAG, "onResponse: 类型----"+advRequestModle.getPriceType()+"价格---"+advRequestModle.getPlayPriceStr());
                                Message msg = Message.obtain();
                                msg.what = EMPTYPLAYERSUCCESS;
                                msg.obj = advRequestModle;
                                mHanler.sendMessage(msg);
                            } else {
                                mHanler.sendEmptyMessage(EMPTYPLAYERFAILURE);
                            }
                        } else {
                            mHanler.sendEmptyMessage(EMPTYPLAYERFAILURE);
                        }
                    } catch (Exception e) {
                        mHanler.sendEmptyMessage(EMPTYPLAYERFAILURE);
                    }
                }
            });
        }

        public void stop() {
            if (null != mHanler) {
                mHanler.removeCallbacksAndMessages(null);
            }
        }
    }

    private AdvInfo topAdv;
    private AdvInfo middleAdv;

    public void group2Play1(ActInfo act, final View view, final String type, final String price) {
        topAdv = null;
        middleAdv = null;
        List<AdvInfo> ads = act.getAds();
        if (ads.size() > 0) {
            if (ads.size() == 2) {
                if ("3".equals(ads.get(0).getAdvType())) {
                    middleAdv = ads.get(0);
                    topAdv = ads.get(1);
                } else if ("5".equals(ads.get(0).getAdvType())) {
                    middleAdv = ads.get(1);
                    topAdv = ads.get(0);
                }
            } else if (ads.size() == 1) {
                if ("3".equals(ads.get(0).getAdvType())) {
                    middleAdv = ads.get(0);
                } else if ("5".equals(ads.get(0).getAdvType())) {
                    topAdv = ads.get(0);
                }
            }
            if (reckonAndCheckExists(topAdv) && reckonAndCheckExists(middleAdv)) {
                //文件存在
                group2PlayBegin(view, topAdv, middleAdv,type,price);
            } else {
                //文件丢失-缓存'
                if (!reckonAndCheckExists(topAdv)) {
                    fileMissCache(topAdv, new DownloadUtilsListener() {
                        @Override
                        public void onComplete() {
                            fileMissCache(middleAdv, new DownloadUtilsListener() {
                                @Override
                                public void onComplete() {
                                    //2个都缓存完成
                                    handler.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            if (null != middleAdv) {
                                                group2PlayBegin(view, topAdv, middleAdv,type,price);
                                            } else {
                                                group2PlayBegin(view, topAdv, null,"","");
                                            }
                                        }
                                    });
                                }
                            });
                        }
                    });
                } else if (!reckonAndCheckExists(middleAdv)) {
                    fileMissCache(middleAdv, new DownloadUtilsListener() {
                        @Override
                        public void onComplete() {
                            //2个都缓存完成
                            if (null != middleAdv) {
                                group2PlayBegin(view, topAdv, middleAdv,type,price);
                            } else {
                                group2PlayBegin(view, topAdv, null,"","");
                            }
                        }
                    });
                } else {
                    standbyPlay();
                }
            }
        } else {
            standbyPlay();
        }
    }

    private void group2PlayBegin(View view, final AdvInfo topAdv, final AdvInfo middleAdv, final String type, final String price) {
        viewManager.display(view);
        String vedPath = null;
        if (null != middleAdv) {
            vedPath = middleAdv.getPath();
        }
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                ostmsStandbyPlayer.ostmsStandbyPlayStart();
            }
        }, Tools.getRandomNum(3, 9, 1));
        topAdv.setTriggerTime(new Date().getTime() + "");
        middleAdv.setTriggerTime(new Date().getTime() + "");

        topAdv.setCode(Md5Util.MD5(new Date().getTime() + Tools.initEquipmentCode()));
        middleAdv.setCode(Md5Util.MD5(new Date().getTime() + Tools.initEquipmentCode()));
        group2Player.play(topAdv, vedPath, new VideoPlay() {
            @Override
            public void onPlayCompletion() {
                List<AdvInfo> list = new ArrayList<>();
                list.add(topAdv);
                list.add(middleAdv);
                record(list, false,type,price);
                standbyPlay();
            }
        });
    }

    private List<AdvInfo> getDrawableList() {
        AdvInfo adv1 = new AdvInfo();
        adv1.setDrawable(true);
        adv1.setDrawablePath("drawable://" + R.drawable.d001);

        AdvInfo adv2 = new AdvInfo();
        adv2.setDrawable(true);
        adv2.setDrawablePath("drawable://" + R.drawable.d002);

        AdvInfo adv3 = new AdvInfo();
        adv3.setDrawable(true);
        adv3.setDrawablePath("drawable://" + R.drawable.d003);

        AdvInfo adv4 = new AdvInfo();
        adv4.setDrawable(true);
        adv4.setDrawablePath("drawable://" + R.drawable.d004);

        AdvInfo adv5 = new AdvInfo();
        adv5.setDrawable(true);
        adv5.setDrawablePath("drawable://" + R.drawable.d005);

        List<AdvInfo> ads = new ArrayList<>();
        ads.add(adv1);
        ads.add(adv2);
        ads.add(adv3);
        ads.add(adv4);
        ads.add(adv5);
        return ads;
    }

    private void fileMissCache(final AdvInfo advInfo, final DownloadUtilsListener listener) {
        if (null != advInfo) {
            final String dir = CommonUtils.ADV_PATH + (isVedio(advInfo) ? "/video" : "/image");
            final String url = advInfo.getUrl();
            String suffix = url.substring(url.lastIndexOf(".") + 1, url.length());
            final String fileName = advInfo.getAdvCode() + "." + suffix;
            final String path = Environment.getExternalStorageDirectory().getAbsolutePath() + dir + "/" + fileName;
            advInfo.setPath(path);
            if (!new File(path).exists()) {
                new HttpTools(context).downloadAdv(url, dir, advInfo.getAdvCode(), new HttpTools.OnDownloadListener1() {
                    @Override
                    public void onDownloadSuccess() {
                        log.i(TAG, advInfo.getAdvCode() + ":下载成功：onDownloadSuccess");
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                listener.onComplete();
                            }
                        });
                    }

                    @Override
                    public void onDownloadFailed(Throwable e) {
                        log.i(TAG, advInfo.getAdvCode() + ":下载失败：onDownloadFailed" + e);
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                listener.onComplete();
                            }
                        });
                    }
                });
            } else {
                listener.onComplete();
            }
        } else {
            listener.onComplete();
        }
    }

    public interface DownloadUtilsListener {
        void onComplete();
    }

    /**
     * 定义视频播放接口
     */
    private MediaPlayer mMediaPlayer;

    public abstract class VideoPlay {

        public void play(Surface surface, String path) {
            try {
                //根据本地视频资源初始化视频播放器
                final long time1 = System.currentTimeMillis();
//                initPlayer(surface, path);
                mMediaPlayer = new MediaPlayer();
                mMediaPlayer.reset();
                mMediaPlayer.setDataSource(path);
                mMediaPlayer.prepareAsync();
                mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                mMediaPlayer.setSurface(surface);
                //设置播放完成监听
                mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        long time2 = System.currentTimeMillis();
                        if (time2 - time1 < 5 * 1000) {
                            handler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    System.gc();
                                    release();
                                    onPlayCompletion();
                                }
                            }, 5 * 1000);
                        } else {
                            System.gc();
                            release();
                            onPlayCompletion();
                        }
                    }
                });
                //设置准备完成直接开始
                OnPreparedStart();
                mMediaPlayer.setOnSeekCompleteListener(new MediaPlayer.OnSeekCompleteListener() {
                    @Override
                    public void onSeekComplete(MediaPlayer mp) {
                        mp.seekTo(0);
                    }
                });
            } catch (Throwable e) {
                log.e(TAG + ".VideoPlay", e);
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        System.gc();
                        release();
                        onPlayCompletion();
                    }
                }, 5 * 1000);
            }
        }

        public abstract void onPlayCompletion();

        /**
         * 准备播放之后监听--直接开始播放
         */
        private void OnPreparedStart() {
            mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mp.start();
                }
            });
        }

        /**
         * 释放播放器
         */
        private void release() {
            if (null != mMediaPlayer) {
                if (mMediaPlayer.isPlaying()) {
                    mMediaPlayer.stop();
                }
                mMediaPlayer.reset();
                mMediaPlayer.release();
                mMediaPlayer = null;
            }
        }

    }

    private void record(List<AdvInfo> advList, boolean isBottom,String type,String price) {
        if (advList.size() > 0) {
            String path = CommonUtils.RECORD;
            MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
            List<RecordModle> listRecord = new ArrayList<>();
            if (null != advList && advList.size() > 0) {
                for (int i = 0; i < advList.size(); i++) {
                    try {
                        AdvInfo adv = advList.get(i);
                        RecordModle recordModle = new RecordModle();
                        //设备编号
                        recordModle.setEquipmentCode(Tools.initEquipmentCode());
                        //广告编号
                        recordModle.setAdvCode(adv.getAdvCode());
                        //合同编号
                        recordModle.setConCode(adv.getConCode());
                        //触发时间
                        recordModle.setParam1(adv.getTriggerTime() + "");
                        recordModle.setAdvType(adv.getAdvType() + "");
                        recordModle.setTriggerCode(adv.getCode());
                        recordModle.setPriceType(type);
                        recordModle.setPlayPriceStr(price);
                        recordModle.setConType(adv.getConType());
                        Log.i(TAG, "record: 播放接受到"+type+"---"+price+"---"+adv.getConType());
                        //播放完成时间
                        recordModle.setParam2(new Date().getTime() + "");
                        if (adv.getWinNoticeUrl() != null) {
                            recordModle.setWinNoticeUrl(adv.getWinNoticeUrl());
                        }
                        if (adv.getThirdMonitorUrl() != null) {
                            recordModle.setThirdMonitorUrl(adv.getThirdMonitorUrl());
                        }
                        if (null != adv.getId()) {
                            recordModle.setId(adv.getId());
                        }
                        listRecord.add(recordModle);
                    } catch (Exception e) {
                        log.e(TAG + "播放记录参数异常", e);
                    }
                }
                Gson gson = new Gson();
                String listRecordJson = gson.toJson(listRecord);
                builder.addFormDataPart("listRecord", listRecordJson);
                System.out.println("广告字符串：" + listRecordJson);
                httpTools.upLoadFile(path, builder, new HttpTools.HttpLisenner() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        log.i(TAG, "record播放记录错误:" + e);
                    }

                    @Override
                    public void onResponse(Call call, String result) {
                        log.i(TAG, "record播放记录:" + result);
                    }
                });
            }
        }
    }
}
